package com.imooc.service.impl;

import com.imooc.enums.OrderStatusEnum;
import com.imooc.enums.YesOrNo;
import com.imooc.mapper.OrderItemsMapper;
import com.imooc.mapper.OrderStatusMapper;
import com.imooc.mapper.OrdersMapper;
import com.imooc.pojo.*;
import com.imooc.pojo.bo.ShopCartBO;
import com.imooc.pojo.bo.SubmitOrderBO;
import com.imooc.pojo.vo.MerchantOrdersVO;
import com.imooc.pojo.vo.OrderVO;
import com.imooc.service.AddressService;
import com.imooc.service.ItemService;
import com.imooc.service.OrderService;
import com.imooc.utils.DateUtil;
import com.imooc.utils.RedisOperator;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: foodie-dev
 * @description: 订单接口实现
 * @author: rZ
 * @create: 2020-06-26 11:46
 **/
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private AddressService addressService;

    @Autowired
    private ItemService itemService;

    @Autowired
    private OrderItemsMapper orderItemsMapper;

    @Autowired
    private OrderStatusMapper orderStatusMapper;

    @Autowired
    private Sid sid;

    @Autowired
    private RedisOperator redisOperator;

    /**
     * 创建订单
     * @param submitOrderBO
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public OrderVO createOrder(List<ShopCartBO> shopCartList,SubmitOrderBO submitOrderBO) {
        //用户id
        String userId = submitOrderBO.getUserId();
        //地址id
        String addressId = submitOrderBO.getAddressId();
        //规格ids
        String itemSpecIds = submitOrderBO.getItemSpecIds();
        //支付方式
        Integer payMethod = submitOrderBO.getPayMethod();
        //买家留言
        String leftMsg = submitOrderBO.getLeftMsg();
        //包邮费用设置为0
        Integer postAmount = 0 ;

        String orderId = sid.nextShort();
        UserAddress userAddress = addressService.queryUserAddress(userId, addressId);

        //1.新订单数据保存
        Orders newOrder = new Orders();
        newOrder.setId(orderId);
        newOrder.setUserId(userId);
        newOrder.setReceiverName(userAddress.getReceiver());
        newOrder.setReceiverMobile(userAddress.getMobile());
        newOrder.setReceiverAddress(userAddress.getProvince()+" "+
                                    userAddress.getCity()+" "+
                                    userAddress.getDistrict()+" "+
                                    userAddress.getDetail());
        newOrder.setPostAmount(postAmount);
        newOrder.setPayMethod(payMethod);
        newOrder.setLeftMsg(leftMsg);
        newOrder.setIsComment(YesOrNo.NO.type);
        newOrder.setIsDelete(YesOrNo.NO.type);
        newOrder.setCreatedTime(new Date());
        newOrder.setUpdatedTime(new Date());

        //2.根据itemSpecIds保存订单商品信息表
        String[] itemSpecIdAddr = itemSpecIds.split(",");
        //商品原价累加的总价格
        Integer totalAmount = 0;
        //优惠后的实际支付价格累计
        Integer realPayAmount = 0;
        List<ShopCartBO> toBeRemoveShopCartList = new ArrayList<>();
        for (String itemSpecId : itemSpecIdAddr) {
            ShopCartBO cartItem = getBuyCountsFromShopCart(shopCartList, itemSpecId);
            // 整合redis后，商品购买的数量重新从redis的购物车中获取
            int buyCount = cartItem.getBuyCounts();
            toBeRemoveShopCartList.add(cartItem);
            //2.1 根据规格id，查询规格的具体信息，主要获取价格
            ItemsSpec itemsSpec = itemService.queryItemSpecById(itemSpecId);
            totalAmount += itemsSpec.getPriceNormal() * buyCount;
            realPayAmount += itemsSpec.getPriceDiscount() * buyCount;

            //2.2 根据商品id，获得商品信息以及商品图片
            String itemId = itemsSpec.getItemId();
            Items items = itemService.queryItemById(itemId);
            String imgUrl = itemService.queryItemMainImgById(itemId);

            //2.3循环保存自订单
            String subOrderId = sid.nextShort();
            OrderItems subOrderItem = new OrderItems();
            subOrderItem.setId(subOrderId);
            subOrderItem.setOrderId(orderId);
            subOrderItem.setItemId(itemId);
            subOrderItem.setItemName(items.getItemName());
            subOrderItem.setItemImg(imgUrl);
            subOrderItem.setBuyCounts(buyCount);
            subOrderItem.setItemSpecId(itemSpecId);
            subOrderItem.setItemSpecName(itemsSpec.getName());
            subOrderItem.setPrice(itemsSpec.getPriceDiscount());
            orderItemsMapper.insert(subOrderItem);

            //2.4 在用户提交订单以后，规格表中需要扣除库存
            itemService.decreaseItemSpecStock(itemSpecId,buyCount);
        }
        newOrder.setTotalAmount(totalAmount);
        newOrder.setRealPayAmount(realPayAmount);
        ordersMapper.insert(newOrder);
        //3.保存订单状态表
        OrderStatus waitPayOrderStatus = new OrderStatus();
        waitPayOrderStatus.setOrderId(orderId);
        waitPayOrderStatus.setOrderStatus(OrderStatusEnum.WAIT_PAY.type);
        waitPayOrderStatus.setCreatedTime(new Date());
        orderStatusMapper.insert(waitPayOrderStatus);

        //4.构建商户订单，用于传给支付中心
        MerchantOrdersVO merchantOrdersVO = new MerchantOrdersVO();
        merchantOrdersVO.setMerchantOrderId(orderId);
        merchantOrdersVO.setMerchantUserId(userId);
        merchantOrdersVO.setAmount(realPayAmount + postAmount);
        merchantOrdersVO.setPayMethod(payMethod);
        //5.构建自定义订单vo
        OrderVO orderVO = new OrderVO();
        orderVO.setOrderId(orderId);
        orderVO.setMerchantOrdersVO(merchantOrdersVO);
        orderVO.setToBeRemoveShopCartList(toBeRemoveShopCartList);
        return orderVO;
    }

    /**
     * 修改订单状态
     * @param OrderId
     * @param orderStatus
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void updateOrderStatus(String OrderId, Integer orderStatus) {
        OrderStatus paidStatus = new OrderStatus();
        paidStatus.setOrderId(OrderId);
        paidStatus.setOrderStatus(orderStatus);
        paidStatus.setPayTime(new Date());
        orderStatusMapper.updateByPrimaryKeySelective(paidStatus);
    }

    /**
     * 查询订单状态
     * @param orderId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public OrderStatus queryOrderStatusInfo(String orderId) {
        return orderStatusMapper.selectByPrimaryKey(orderId);
    }

    /**
     * 关闭超时未支付订单
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void closeOrder() {
        //查询所有未支付订单，判断时间是否超时（1天），超时则关闭交易
        OrderStatus queryOrder = new OrderStatus();
        queryOrder.setOrderStatus(OrderStatusEnum.WAIT_PAY.type);
        List<OrderStatus> orderStatusList = orderStatusMapper.select(queryOrder);
        for (OrderStatus orderStatus : orderStatusList) {
            //获取订单创建时间
            Date createdTime = orderStatus.getCreatedTime();
            //和当前时间进行对比
            int days = DateUtil.daysBetween(createdTime, new Date());
            if (days >= 1){
                //超过一天关闭订单
                doCloseOrder(orderStatus.getOrderId());
            }
        }
    }

    /**
     * 关闭订单，更新数据库
     * @param orderId
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void doCloseOrder(String orderId){
        OrderStatus closeOrder = new OrderStatus();
        closeOrder.setOrderId(orderId);
        closeOrder.setOrderStatus(OrderStatusEnum.CLOSE.type);
        closeOrder.setCloseTime(new Date());
        orderStatusMapper.updateByPrimaryKeySelective(closeOrder);
    }

    /**
     * 从redis中的购物车里获取商品，目的：counts
     * @param shopCartList
     * @param specId
     * @return
     */
    private ShopCartBO getBuyCountsFromShopCart(List<ShopCartBO> shopCartList,String specId){
        for (ShopCartBO shopCartBO : shopCartList) {
            if (shopCartBO.getSpecId().equals(specId)){
                return shopCartBO;
            }
        }
        return null;
    }
}
